package com.taoyeshu.modules.sys.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.taoyeshu.modules.sys.entity.Resource;

public class ResUtil {
	/**
	 * 根据父节点的ID获取所有子节点
	 * 
	 * @param list
	 *            分类表
	 * @param typeId
	 *            传入的父节点ID
	 * @return String
	 */
	public List<Resource> getChildTreeObjects(List<Resource> list, int praentId) {
		List<Resource> returnList = new ArrayList<Resource>();
		for (Iterator<Resource> iterator = list.iterator(); iterator.hasNext();) {
			Resource t = (Resource) iterator.next();
			// 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
			if (t.getParent().getId() == praentId) {
				recursionFn(list, t);
				returnList.add(t);
			}
		}
		return returnList;
	}

	/**
	 * 递归列表
	 * 
	 * @author lanyuan Email: mmm333zzz520@163.com
	 * @date 2013-12-4 下午7:27:30
	 * @param list
	 * @param TreeObject
	 */
	private void recursionFn(List<Resource> list, Resource t) {
		List<Resource> childList = getChildList(list, t);// 得到子节点列表
		t.setChildren(childList);
		for (Resource tChild : childList) {
			if (hasChild(list, tChild)) {// 判断是否有子节点
				// returnList.add(TreeObject);
				Iterator<Resource> it = childList.iterator();
				while (it.hasNext()) {
					Resource n = (Resource) it.next();
					recursionFn(list, n);
				}
			}
		}
	}

	// 得到子节点列表
	private List<Resource> getChildList(List<Resource> list, Resource t) {

		List<Resource> tlist = new ArrayList<Resource>();
		Iterator<Resource> it = list.iterator();
		while (it.hasNext()) {
			Resource n = (Resource) it.next();
			if (n.getParent().getId() == t.getId()) {
				tlist.add(n);
			}
		}
		return tlist;
	}

	// 判断是否有子节点
	private boolean hasChild(List<Resource> list, Resource t) {
		return getChildList(list, t).size() > 0 ? true : false;
	}
}
